/*
 * 文件名：EffectSureController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wangw
 * 修改时间：2020年2月18日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.bpa.web;


import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.bpa.domain.EffectSureDomain;
import top.infopub.mgr.bpa.service.EffectPlanDetailService;
import top.infopub.mgr.bpa.service.EffectPlanService;
import top.infopub.mgr.bpa.service.EffectSureService;
import top.infopub.mgr.bpa.service.ProContractService;
import top.infopub.mgr.bpa.vo.EffectSureVo;
import top.infopub.mgr.bpa.vo.ProContractVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.DateUtils;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.bpa.EffectPlan;
import top.infopub.model.bpa.EffectPlanDetail;
import top.infopub.model.bpa.EffectSureAtt;
import top.infopub.model.bpa.EffectSureDetail;
import top.infopub.model.bpa.ProContract;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * @author wangw
 * @version 2020年2月18日
 * @see EffectSureController
 * @since
 */
@Controller
@RequestMapping("/effectSure")
public class EffectSureController extends GenericFlowController {

    @Autowired
    private OrgInfoService orgInfoService;

    @Autowired
    private EffectSureService effectSureService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private ProContractService proContractService;

    @Autowired
    private EffectPlanService effectPlanService;

    @Autowired
    private EffectPlanDetailService effectPlanDetailService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 跳转列表页
     *
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        return "bpa/lay-effectSure-list";
    }

    /**
     * 创效确认列表数据
     *
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<EffectSureDomain> queryDataByCondition(EffectSureVo effectSureVo,
                                                        ParamPage paramPage,
                                                        String monthStartDateStr,
                                                        String monthEndDateStr) {
        Page<EffectSureDomain> page = new Page<EffectSureDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (effectSureVo.getEndDate() != null) {
            effectSureVo.setEndDate(DateUtils.addDays(effectSureVo.getEndDate(), 1));
        }
        //查询时，创效月份开始日期
        if (StringUtils.isNotEmpty(monthStartDateStr)) {
            effectSureVo.setMonthStartDate(DateUtils.convertToDate(monthStartDateStr + "-01"));
        }
        //查询时，创效月份结束日期增加一天
        if (StringUtils.isNotEmpty(monthEndDateStr)) {
            effectSureVo.setMonthEndDate(DateUtils.getMonthEnd(DateUtils.convertToDate(
                monthEndDateStr, "yyyy-MM")));
        }
        page = effectSureService.selectPageByDomainWhere(page, effectSureVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 创效确认-我审批的列表数据
     *
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<EffectSureDomain> queryMyCheckDataByCondition(EffectSureVo effectSureVo,
                                                               ParamPage paramPage,
                                                               String monthStartDateStr,
                                                               String monthEndDateStr) {
        Page<EffectSureDomain> page = new Page<EffectSureDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (effectSureVo.getEndDate() != null) {
            effectSureVo.setEndDate(DateUtils.addDays(effectSureVo.getEndDate(), 1));
        }
        //查询时，创效月份开始日期
        if (StringUtils.isNotEmpty(monthStartDateStr)) {
            effectSureVo.setMonthStartDate(DateUtils.convertToDate(monthStartDateStr + "-01"));
        }
        //查询时，创效月份结束日期增加一天
        if (StringUtils.isNotEmpty(monthEndDateStr)) {
            effectSureVo.setMonthEndDate(DateUtils.getMonthEnd(DateUtils.convertToDate(
                monthEndDateStr, "yyyy-MM")));
        }
        effectSureVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = effectSureService.selectMyCheckByDomainWhere(page, effectSureVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 创效确认-新增
     *
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可公司年度预算的公司年度预算记录
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询所有项目合同
        List<ProContract> contractList = proContractService.selectAllContracts(null, null);
        request.setAttribute("contractList", contractList);
        return "bpa/lay-effectSure-add";
    }

    /**
     * 根据id查询项目合同记录
     *
     * @param id
     * @return
     */
    @RequestMapping("/getProContractById")
    @ResponseBody
    public Map<String, Object> getProContractById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            ProContractVo proContractVo = proContractService.queryById(id);
            if (proContractVo != null) {
                map.put("proContractVo", proContractVo);
            }
        }
        catch (Exception e) {
            log.error("查询项目合同记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据月份和项目编号查询创效计划记录
     * @param id
     * @return
     */
    @RequestMapping("/getEffectPlanByMonthAndProCode")
    @ResponseBody
    public Map<String, Object> getEffectPlanByMonthAndProCode(String effectMonth, String proCode) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isBlank(effectMonth) || StringUtils.isBlank(proCode)) {
            flag = false;
        }
        else {
            try {
                int belongsYear = Integer.parseInt(effectMonth.split("-")[0]);
                int months = Integer.parseInt(effectMonth.split("-")[1]);
                EffectPlan effectPlanWhere = new EffectPlan();
                effectPlanWhere.setProCode(proCode);
                effectPlanWhere.setBelongsYear(belongsYear);
                effectPlanWhere.setProcessStatus("9");//审批通过
                EffectPlan effectPlan = effectPlanService.selectLastedEffectPlan(effectPlanWhere);
                if (effectPlan != null) {
                    //年计划创效金额
                    map.put("yearPlanAmount", effectPlan.getYearPlanAmount());
                    EffectPlanDetail effectPlanDetailWhere = new EffectPlanDetail();
                    effectPlanDetailWhere.setEffectPlanId(effectPlan.getId());
                    effectPlanDetailWhere.setMonths(months);
                    EffectPlanDetail effectPlanDetail = effectPlanDetailService.selectByEntityWhere(
                        effectPlanDetailWhere).get(0);
                    //月计划创效金额
                    map.put("monthPlanAmount", effectPlanDetail.getMonthPlanAmount());

                    String startDate = effectMonth.split("-")[0] + "-01-01 00:00:00";//年度第一天
                    String endDate = effectMonth.split("-")[0] + "-12-31 23:59:59";//年度第一天
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    EffectSureVo effectSureVo = new EffectSureVo();
                    effectSureVo.setStartDate(sdf.parse(startDate));
                    effectSureVo.setEndDate(sdf.parse(endDate));
                    effectSureVo.setProCode(proCode);
                    //年度累计创效金额
                    BigDecimal totalEffectSureAmount = effectSureService.selectTotalAmount(effectSureVo);
                    map.put("totalEffectSureAmount", totalEffectSureAmount);
                }
                else {
                    flag = false;
                }
            }
            catch (Exception e) {
                log.error("查询创效计划记录异常", e);
                flag = false;
            }
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 创效确认-新增
     * @throws ParseException 
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(HttpServletRequest request, EffectSureVo effectSure)
        throws ParseException {
        String[] fileAtt = request.getParameterValues("fileAtt");
        String hrStaffApplyid = request.getParameter("effectStaffApplyid");
        String hrOrgid = request.getParameter("effectOrgid");
        String hrDeptid = request.getParameter("effectDeptid");
        String staffname = request.getParameter("staffname");
        String effectMonth = effectSure.getEffectMonth();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        //根据项目id,查出项目的其他信息  此时的proCode存放的时项目合同的Id
        effectSure.setId(id);
        effectSure.setBelongsMonth(sdf.parse(effectMonth));
        effectSure.setHrStaffApplyId(hrStaffApplyid);
        effectSure.setHrOrgId(hrOrgid);
        effectSure.setHrDeptId(hrDeptid);
        //StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(vo.getHrStaffId());
        effectSure.setStaffName(staffname);
        //effectSure.setHrStaffApplyId(vo.getHrStaffId());
        effectSure.setAddBy(vo.getId());
        effectSure.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("bpa_effect_sure");
        effectSure.setCodes(codes);
        effectSure.setProcessId(IdFactory.getUUIDUpper());
        //设置审批状态
        effectSure.setProcessStatus("1");
        effectSure.setUptBy(vo.getId());
        effectSure.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //子表数据处理
        List<EffectSureDetail> effectSureDetailList = new ArrayList<EffectSureDetail>();
        for (EffectSureDetail effectSureDetail : effectSure.getEffectSureDetails()) {
            String detailId = IdFactory.getUUIDUpper();
            effectSureDetail.setId(detailId);
            effectSureDetail.setEffectSureId(id);
            effectSureDetail.setAddBy(vo.getId());
            effectSureDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            effectSureDetailList.add(effectSureDetail);
        }

        List<EffectSureAtt> effectSureAtts = new ArrayList<EffectSureAtt>();
        if (fileAtt != null) {
            for (String file : fileAtt) {
                EffectSureAtt effectSureAtt = createFileAtt(vo, id, file);
                effectSureAtts.add(effectSureAtt);
            }
        }
        effectSureService.save(effectSure, effectSureDetailList, effectSureAtts);
        LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
            "商务管理 -商务事项-新增创效确认：项目名=" + effectSure.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 根据id查询创效确认详细  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 投建项目id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        EffectSureVo effectSure = effectSureService.queryById(id);
        OrgInfo orgInfo = new OrgInfo();
        orgInfo.setProjectCode(effectSure.getProCode());
        orgInfo.setState(1);
        List<OrgInfo> orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        if (orgInfos.size() > 0) {
            effectSure.setOrgProName(orgInfos.get(0).getCompName());
            effectSure.setHrOrgProId(orgInfos.get(0).getId());
            OrgInfo parentOrgInfo = new OrgInfo();
            parentOrgInfo.setId(orgInfos.get(0).getParentId());
            parentOrgInfo.setState(1);
            List<OrgInfo> parentOInfos = orgInfoService.selectByEntityWhere(parentOrgInfo);
            if (parentOInfos.size() > 0) {
                effectSure.setOrgAreName(parentOInfos.get(0).getCompName());
                effectSure.setHrOrgAreaId(parentOInfos.get(0).getId());
            }
        }
        map.put("effectSure", effectSure);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, effectSure.getProcessId());
        return new ModelAndView("bpa/lay-effectSure-detail", map);
    }

    private EffectSureAtt createFileAtt(AuthorizationVO vo, String effectSureId, String file) {
        //附件信息数组
        String[] fileAttStr = file.split("\\|");
        EffectSureAtt fileAtt = new EffectSureAtt();
        fileAtt.setId(IdFactory.getUUIDSerialNumber());
        fileAtt.setEffectSureId(effectSureId);//项目id
        String fileName = fileAttStr[0].substring(0, fileAttStr[0].lastIndexOf("."));
        String suffix = fileAttStr[0].substring(fileAttStr[0].lastIndexOf("."),
            fileAttStr[0].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[2]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "effectSureAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 创效确认-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request) {
        String id = request.getParameter("id");
        EffectSureVo effectSureVo = effectSureService.queryById(id);
        request.setAttribute("effectSure", effectSureVo);
        return "bpa/lay-effectSure-copy";
    }

}
